﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using LiveCharts;
using LiveCharts.Wpf;
using 数据挖掘实验.Logger;

namespace 数据挖掘实验
{
    /// <summary>
    /// 先验概率算法
    /// </summary>
    public partial class MainWindow
    {
        AprioriCollector aprioriCollector = new AprioriCollector();

        void InitialApriori()
        {
            LogManager.AprioriLogger.onLog += (info, newInfo) =>
            {
                AprioriOutput.Document.Blocks.Add(RichTextFormatter.Format(newInfo));
            };

            InitialAprioriChart();
        }

        void InitialAprioriChart()
        {
            aprioriAxisT.Title = "支持度/%";
            aprioriAxisT.LabelFormatter = value => $"{value * 100:0.00}%";
            AprioriChart.DataClick += AprioriChartClickData;
        }

        bool confidenceMode = false;

        void AprioriChartClickData(object sender, ChartPoint chartPoint)
        {
            if (confidenceMode)
                return;
            
            var item = AprioriItems[chartPoint.Key];
            var values = item.ConfidenceCollector.Select(x => x.Confidence).ToArray();
            var labels = item.ConfidenceCollector.Select(x => x.GetItemsStr(aprioriCollector.Transaction))
                .ToArray();
            AprioriDrawChartByInfo(values, labels, "项集", "置信度");

            confidenceMode = true;
        }

        void AprioriChartBackToSupport(object sender, MouseButtonEventArgs e)
        {
            if (!confidenceMode)
                return;
            
            confidenceMode = false;
            AprioriDrawChartByInfo(AprioriSupportValues, AprioriLabels, "项集", "支持度");
        }

        void Apriori_Recognition_Click(object sender, RoutedEventArgs e)
        {
            LogManager.AprioriLogger.Clear();
            AprioriOutput.Document.Blocks.Clear();
            aprioriCollector.Compute();
            AprioriDrawChart();
        }

        AprioriItem[] AprioriItems;
        float[] AprioriSupportValues;
        string[] AprioriLabels;
        ColumnSeries aprioriPercentColumn;

        void AprioriDrawChart()
        {
            confidenceMode = false;
            aprioriPercentColumn = new ColumnSeries {ScalesYAt = 0};
            AprioriChart.Series = new SeriesCollection {aprioriPercentColumn};
            var calc = aprioriCollector.Where(x => x.Depth > 1);
            AprioriItems = calc.ToArray();
            AprioriSupportValues = calc.Select(x => x.Support).ToArray();
            AprioriLabels = calc.Select(x => x.GetItemsStr(aprioriCollector.Transaction)).ToArray();
            AprioriDrawChartByInfo(AprioriSupportValues, AprioriLabels, "项集", "支持度");
        }

        void AprioriDrawChartByInfo(float[] values, string[] labels, string title, string subTitle)
        {
            aprioriPercentColumn.Title = subTitle;
            aprioriPercentColumn.Values = new ChartValues<float>(values);
            aprioriAxisV.Title = title;
            aprioriAxisV.Labels = labels;
        }


        void Apriori_File_Read_Button_Click(object sender, RoutedEventArgs e)
        {
            var openFileDialog = new Microsoft.Win32.OpenFileDialog()
            {
                Filter = "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*"
            };
            var result = openFileDialog.ShowDialog();
            if (result == true)
            {
                string path = openFileDialog.FileName;
                AprioriFileNameLabel.Content = path;
                aprioriCollector.Open(path);
            }
        }

        void NumberCheck(object sender, TextCompositionEventArgs e)
        {
            Regex re = new Regex(@"[^\d]"); // 输入框只能输入数字
            e.Handled = re.IsMatch(e.Text);
        }

        void AprioriPercentLimit(object sender, TextChangedEventArgs e)
        {
            var text = e.OriginalSource as TextBox;
            if (text.Text != string.Empty && int.Parse(text.Text) > 100) // 限制最大为100%
            {
                text.Text = "100";
            }

            var aprioriSupportThreshold = 0f;
            var aprioriConfidenceThreshold = 0f;
            if (!string.IsNullOrEmpty(AprioriSupport.Text))
                aprioriSupportThreshold = int.Parse(AprioriSupport?.Text) / 100f;
            if (!string.IsNullOrEmpty(AprioriConfidence?.Text))
                aprioriConfidenceThreshold = int.Parse(AprioriConfidence.Text) / 100f;
            aprioriCollector.SetThreshold(aprioriSupportThreshold, aprioriConfidenceThreshold); // 改变阈值
        }

        /// <summary>
        /// 切换日志/图表模式按钮被按下
        /// </summary>
        void AprioriExhibitChange_Click(object sender, RoutedEventArgs e)
        {
            bayesOutputMode = !bayesOutputMode;
            AprioriOutputScroll.Visibility = ConvertBoolToVisibility(bayesOutputMode);
            AprioriChartScroll.Visibility = ConvertBoolToVisibility(!bayesOutputMode);
        }
    }
}